<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\WishFragmentRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Models\Wish;
use App\Services\Business\Models\WishFragment;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\WishList;
use App\Services\Business\Services\VideoService;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\Activity;
use App\Services\Member\Models\User;
use App\Services\Member\Services\UserService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class WishFragmentController extends BaseController
{


    /**
     * @var VideoService
     */
    protected $videoService;
    /**
     * @var ConfigService
     */
    protected $configService;

    /**
     * @var UserService
     */
    protected $userService;
    protected $businessState;


    public function __construct(

        ConfigServiceInterface $configService,
        UserServiceInterface   $userService,
        VideoServiceInterface  $videoService,
        BusinessState          $businessState

    )
    {
        $this->configService = $configService;
        $this->userService = $userService;
        $this->businessState = $businessState;
        $this->videoService = $videoService;

    }

    public function index(Request $request)
    {


        $size = $request->input('size', 5);

        $activities = WishFragment::query()
            ->with(['images', 'videos'])
            ->orderByDesc('created_at')
            ->paginate($size);

        //发布的人
        $users = User::query()
            ->whereIn('id', array_column($activities->items(), 'user_id'))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');
        return $this->successData(compact('activities', 'users'));

    }


    public
    function store(WishFragmentRequest $request, WishFragment $fragment)
    {

        $userId = $this->id();
        $data = $request->filldata();
        $wish = Wish::query()->where('id', $data['wish_id'])->first();
        DB::transaction(function () use ($fragment, $data, $userId, $wish) {

            //如是新增，wish是减掉积分
            $wish->update(['remain_point' => $wish->remain_point - $data['point']]);
            $fragment->fill($data)->save($data);
            $fragment->images()->createMany($data['images']);
            $fragment->videos()->attach($data['video_ids']);
            $fragment->activity()->save(new Activity(['user_id' => $userId]));
            if ($wish->remain_point - $data['point']< 0)  {
                $wish->update(['status'=>1,'days'=>Carbon::parse($wish->start_at)->diffInDays(Carbon::now())]);
                WishList::create([
                    'user_id' =>$userId,
                    'wish_id' => $wish->id,
                    'point'=>$wish->remain_point,
                    'days' =>Carbon::parse($wish->start_at)->diffInDays(Carbon::now()),
                ]);
            }

        });
        $isFulfilled  = $wish->remain_point <  0 ;
        return $this->successData(compact('isFulfilled'));
    }


    public function edit($id)
    {


        $maxFragment = WishFragment::max('id');
        if ($maxFragment != $id) {
            return $this->error(__('只能编辑最新的动态'));
        }
        $fragment = WishFragment::query()
            ->where('id', $id)
            ->first();

        if (!$fragment) {
            return $this->error(__('动态不存在'));
        }
        // 获取包含图片和视频的记录
        $fragment = WishFragment::query()
            ->with(['images', 'videos'])
            ->where('id', $fragment->id)
            ->first();

        return $this->successData(compact('fragment'));

    }


    public
    function update(WishFragmentRequest $request, $id)
    {
        $fragment = WishFragment::query()->where('id', $id)->first();
        $maxFragment = WishFragment::query()->where('wish_id',$fragment->wish_id)->max('id');
        if ($maxFragment != $id) {
            return $this->error(__('只能编辑最新的动态'));
        }
        $wish = Wish::query()->where('id', $fragment->wish_id)->first();
        $data = $request->filldata();
        DB::transaction(function () use ($fragment, $data, $wish) {

            //如果是更新，则是取差值
            $wish->update(['remain_point' => $wish->remain_point - $data['difference']]);
            $fragment->fill($data)->save($data);
            $fragment->images()->delete();
            $fragment->images()->createMany($data['images']);
            $fragment->videos()->sync($data['video_ids']);

        });
        $isFulfilled  = $wish->remain_point < 0 ;
        return $this->successData(compact('isFulfilled'));

    }


    public
    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {
        $fragment = WishFragment::query()->where('id', $id)->first();
        $maxFragment = WishFragment::query()->where('wish_id',$fragment->wish_id)->max('id');
        if ($maxFragment != $id) {
            return $this->error(__('只能删除最新的动态'));
        }

        $wish = Wish::query()->where('id', $fragment->wish_id)->first();
        DB::transaction(function () use ($fragment, $wish, $videoService, $configService) {

            //删除视频点播的图片
            if ($fragment->images->isNotEmpty()) {
                $fragment->images()->delete();
                $images = $fragment->images->flatMap(function ($image) {
                    return [$image->url, $image->small_url];
                })->toArray();
                Storage::disk('oss')->delete($images);
            }

            //删除阿里云的视频
            if ($fragment->videos->isNotEmpty()) {
                $fragment->videos()->detach();
                $fragment->videos()->delete();
                $videoService->deleteVideo(implode(',', $fragment->videos->pluck('aliyun_video_id')->toArray()), $configService);
            }
               //如是新增，wish是增加积分
            $wish->update(['remain_point' => $wish->remain_point + $fragment->point]);
            $fragment->delete();
        });

        return $this->success(__('删除成功'));
    }



}
